/** 任务详情 */
import {Button, Divider, InputNumber, Modal, Popover, Radio, Space, Spin, Tooltip} from "antd";
import {Graph} from "@antv/x6";
// @ts-ignore
import './index.css'
import {
    buildGraph, prettify, GraphTools, SHAPE_DOT_EDGE, SHAPE_SOLID_EDGE
} from "./definition.tsx";
import {Component, createRef} from "react";
import {Descriptions, message} from "antd";

import {send, URL} from "../../../../utils/http.util.tsx";
import {Handler, nth} from "../../../../utils/util.tsx";
import LazyIcon from "../../Icon";
import {getCertainPrincipal} from "../../../../utils/auth.util.tsx";
import {emptyData, State} from "./types.tsx";
import InstanceDetail from "../Instance";

const UNABLE_TO_PASS_PROMPT = "AI 制图中"

class TaskDetail extends Component<any, State> {
    private graph: Graph | undefined;
    private graphTools: GraphTools | undefined;

    instanceDetailRef = createRef<InstanceDetail>()

    state = {
        visible: false, instanceVisible: false, instanceLoading: false,
        data: emptyData,

        proportionalEdge: null, proportionalModalVisible: false, proportionalModalValue: 100,
        edgeShape: SHAPE_SOLID_EDGE,
        canRedo: false, canUndo: false,

        openTools: false,
        graphLoading: true,
        onClose: nth
    }

    showTaskDetail(param: any, callback = nth) {
        const variable = JSON.parse(param.variable)

        if (!variable) {
            message.error('Variable is required').then(nth);
            return
        }

        const data = {
            taskId: param.id, taskName: param.taskName, instanceId: param.instanceId,
            x6Json: variable?.x6Json, x6Img: variable?.x6Img, riskInfo: variable?.riskInfo,
        }

        send(URL.questionnaireConfig, null, [data.taskName]).then((resp) => {
            const httpCode = resp.data.httpCode;
            if (httpCode === 200) {
                const questionnaire: any | null = resp.data.data;
                send(URL.questionnaireRecord, {
                    "flwInstanceId": data.instanceId, "flwTaskId": data.taskId, "mark": "USER_END"
                }).then(resp => {
                    const httpCode = resp.data.httpCode;
                    if (httpCode === 200) {
                        const records = resp.data.data
                        this.setState({
                            data: {
                                ...data,
                                question: questionnaire?.question, answer: records.length > 0 ? records[0].content : null
                            },
                            visible: true,
                            onClose: callback
                        }, this.showGraphPanel)
                    } else Handler.ofHttpWarn(httpCode)
                }).catch(Handler.ofError)
            } else Handler.ofHttpWarn(httpCode)
        }).catch(Handler.ofError)
    }

    /**
     * Description: 加载流程详情.
     */
    showInstanceDetail(instanceId: string) {
        this.setState({instanceLoading: true}, () => {
            send(URL.instanceDetail, null, [instanceId]).then((resp) => {
                const httpCode = resp.data.httpCode;
                if (httpCode === 200) {
                    const data = resp.data.data;
                    this.instanceDetailRef.current?.showInstanceDetail(data)
                    this.setState({instanceLoading: false})
                } else Handler.ofHttpWarn(httpCode)
            }).catch(Handler.ofError)
        })
    }

    /**
     * Description: 显示股权架构图的 Panel.
     */
    private showGraphPanel() {
        this.setState({graphLoading: true})

        // ~ 处理数据
        let x6Json: any | null = this.state.data.x6Json
        if (!x6Json) {
            message.error('x6Json is required').then(nth)
            return
        }
        if (typeof x6Json === 'string') x6Json = JSON.parse(x6Json)

        let riskInfo = x6Json.hasOwnProperty('riskInfo') ? x6Json.riskInfo : this.state.data.riskInfo
        if (x6Json.hasOwnProperty('x6Json')) {
            x6Json = x6Json.x6Json
            if (typeof x6Json === 'string') x6Json = JSON.parse(x6Json)
        }

        prettify(x6Json)

        this.graph = buildGraph(document.getElementById('container') as HTMLElement, () => this.state)
        this.graph = x6Json ? this.graph.fromJSON(x6Json) : this.graph
        this.graphTools = new GraphTools(this, this.graph).registerEvents()

        // ~ 处理风险提示信息
        console.log('riskInfo:', riskInfo)
        if (riskInfo && riskInfo != '无') {
            const rect = this.graphTools.getRect()
            this.graphTools.addText(riskInfo, rect.width, rect.height)
        }
        console.log('[Graph] Graph modal updated.');
    }

    /**
     * Description: 关闭 Graph Panel.
     * @author <a href="mailto:scorpio.caplike@gmail.com">LiKe</a> @ 2025-06-17 09:39:28
     */
    private hideGraphPanel() {
        this.setState({openTools: false}, () => {
            this.setState({visible: false, data: emptyData}, () => {
                this.graph?.getPlugin('minimap')?.dispose()
                this.graph?.dispose(true)
                this.state.onClose()
            })
        })
    }

    onUndo = () => this.graph?.undo()
    onRedo = () => this.graph?.redo()

    /**
     * Description: 批准.
     * @author <a href="mailto:scorpio.caplike@gmail.com">LiKe</a> @ 2025-05-17 22:34:58
     */
    handleProcess() {
        const instanceId = this.state.data.instanceId
        const principal: {id: string, nickname: string} = getCertainPrincipal()

        this.graphTools?.getPic((dataUri) => {
            // 组织提交的数据对象
            const dto = {
                instanceId: instanceId,
                actorId: principal.id, actorName: principal.nickname,
                aiX6Json: this.graphTools?.getData(),
                aiX6Img: dataUri
            }

            send(URL.instancePass, dto).then((resp) => {
                const httpCode = resp.data.httpCode;
                if (httpCode === 200) {
                    Modal.success({content: "操作成功", onOk: () => this.setState({visible: false})});
                } else Handler.ofHttpWarn(httpCode)
            }).catch(Handler.ofError)
        })
    }

    render() {
        let {visible, data, proportionalModalVisible} = this.state;

        return (
            <>
                <Modal title="任务详情" open={visible} centered keyboard width={"85%"} onCancel={() => this.hideGraphPanel()}
                       footer={
                           [
                               <Tooltip title={"完成制图并将股权架构图发送给用户"} placement={"topRight"}>
                                   <Button type={"primary"} icon={<LazyIcon iconName={"CheckOutlined"}/>} loading={data.x6Json == null} onClick={() => this.handleProcess()}>
                                       {data.x6Json == null ? UNABLE_TO_PASS_PROMPT : "批准"}
                                   </Button>
                               </Tooltip>
                           ]
                       }
                >
                    <Spin size={"small"} spinning={this.state.instanceLoading}>
                        <Descriptions size={"small"} bordered>
                            <Descriptions.Item label="问卷 ID" labelStyle={{padding: '16px 24px'}}>
                                <Button type={"link"} onClick={() => this.showInstanceDetail(data.instanceId)}>{data.instanceId}</Button>
                            </Descriptions.Item>
                        </Descriptions>
                    </Spin>
                    <Descriptions bordered layout="vertical" style={{marginTop: '10px'}}>
                        <Descriptions.Item label={"股权架构"}>
                            <Spin size={"large"} spinning={data.x6Json == null || this.state.graphLoading} tip={UNABLE_TO_PASS_PROMPT}>
                                <div style={{width: '100%', height: '65vh'}}>
                                    <Modal title={"请输出股权占比"} open={proportionalModalVisible} okText="确定" onOk={() => (this.graphTools as GraphTools).setEdgeLabel()} cancelText="不设占比" onCancel={() => this.setState({proportionalModalVisible: false})}>
                                        <InputNumber style={{width: '100%'}} addonAfter="%" defaultValue={100} min={1} max={100} onChange={(val) => {
                                            if (val == null) {
                                                return
                                            }
                                            this.setState({proportionalModalValue: val})
                                        }}/>
                                    </Modal>
                                    <div id={"container"}></div>
                                </div>
                                <div id={"minimap-container"} className="minimap"/>
                                <Popover placement="topLeft" trigger={"click"} open={this.state.openTools} onOpenChange={(state) => this.setState({openTools: state})} content={
                                    <>
                                        <Button block icon={<LazyIcon iconName={"PicCenter"}/>} onClick={() => (this.graphTools as GraphTools).center()} style={{width: '48%'}}>居中</Button>
                                        <Button block icon={<LazyIcon iconName={"Shrink"}/>} onClick={() => (this.graphTools as GraphTools).fit()} style={{width: '48%', float: 'right'}}>适应</Button>
                                        <Button className={"margin-top"} icon={<LazyIcon iconName={"Undo"}/>} onClick={this.onUndo} disabled={!this.state.canUndo} style={{width: '48%'}}>撤销</Button>
                                        <Button className={"margin-top"} icon={<LazyIcon iconName={"Redo"}/>} onClick={this.onRedo} disabled={!this.state.canRedo} style={{width: '48%', float: 'right'}}>重做</Button>
                                        <Divider style={{margin: '12px 0px'}}/>
                                        <Radio.Group style={{display: 'flex', width: '100%'}} className={"margin-top"} defaultValue={SHAPE_SOLID_EDGE} buttonStyle="solid" onChange={(e) => this.setState({edgeShape: e.target.value})}>
                                            <Radio.Button style={{flex: 1, textAlign: 'center'}} value={SHAPE_SOLID_EDGE}>实线</Radio.Button>
                                            <Radio.Button style={{flex: 1, textAlign: 'center'}} value={SHAPE_DOT_EDGE}>虚线</Radio.Button>
                                        </Radio.Group>
                                        <Divider style={{margin: '12px 0px'}}/>
                                        <Space>
                                            <Button icon={<LazyIcon iconName={"Plus"}/>} block onClick={() => (this.graphTools as GraphTools).addRect()}>添加公司</Button>
                                            {/*<Button icon={<LazyIcon iconName={"Plus"}/>} block onClick={() => (this.graphTools as GraphTools).addCompany()}>添加主体公司</Button>*/}
                                            {/*<Button className={"margin-top"} icon={<LazyIcon iconName={"Plus"}/>} block onClick={() => (this.graphTools as GraphTools).addFamilyCompany()}>添加家族公司</Button>*/}
                                            {/*<Button className={"margin-top"} icon={<LazyIcon iconName={"Plus"}/>} block onClick={() => (this.graphTools as GraphTools).addPlatformCompany()}>添加平台公司</Button>*/}
                                            {/*<Button className={"margin-top"} icon={<LazyIcon iconName={"Plus"}/>} block onClick={() => (this.graphTools as GraphTools).addOtherCompany()}>添加其他投资板块公司</Button>*/}
                                            {/*<Button className={"margin-top"} icon={<LazyIcon iconName={"Plus"}/>} block onClick={() => (this.graphTools as GraphTools).addInvestor()}>添加投资方</Button>*/}
                                            {/*<Button className={"margin-top"} icon={<LazyIcon iconName={"Plus"}/>} block onClick={() => (this.graphTools as GraphTools).addShareHolder()}>添加员工持股平台</Button>*/}
                                            {/*<Button icon={<LazyIcon iconName={"Plus"}/>} style={{marginTop: 8}} block onClick={() => (this.graphTools as GraphTools).addNewCompany()}>添加拟新设公司</Button>*/}
                                            {/*<Button icon={<LazyIcon iconName={"Plus"}/>} style={{marginTop: 8}} block onClick={() => (this.graphTools as GraphTools).addCanceledCompany()}>添加拟注销公司</Button>*/}

                                            <Button icon={<LazyIcon iconName={"Plus"}/>} block onClick={() => (this.graphTools as GraphTools).addRound()}>添加自然人</Button>
                                            {/*<Button icon={<LazyIcon iconName={"Plus"}/>} block onClick={() => (this.graphTools as GraphTools).addPartner()}>添加合伙人</Button>*/}
                                            {/*<Button className={"margin-top"} icon={<LazyIcon iconName={"Plus"}/>} block onClick={() => (this.graphTools as GraphTools).addHolder()}>添加代持人</Button>*/}
                                            <Button icon={<LazyIcon iconName={"Plus"}/>} block onClick={() => (this.graphTools as GraphTools).addText(null, null, null)} type={"dashed"}>添加文本框</Button>
                                        </Space>
                                        <Divider style={{margin: '12px 0px'}}/>
                                        <Button block icon={<LazyIcon iconName={"Export"}/>} onClick={() => (this.graphTools as GraphTools).exportPic()}>导出</Button>
                                    </>
                                }>
                                    <Button className={"toolbox-btn"} icon={<LazyIcon iconName={"Edit"}/>}>工具箱</Button>
                                </Popover>
                            </Spin>
                        </Descriptions.Item>
                    </Descriptions>
                </Modal>

                <InstanceDetail ref={this.instanceDetailRef}></InstanceDetail>
            </>
        )
    }
}

export default TaskDetail;
